<template>
  <div>
    <el-dialog
      :title="showTitle"
      :visible="showDialog"
      width="500px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form ref="form" label-width="80px" :model="formData" :rules="rules">
        <el-form-item label="所属小区" prop="community_code">
          <el-select v-model="formData.community_code" placeholder="请选择活动区域">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入"
          />
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-button
            type="primary"
            size="small"
            @click="addprojectlistFn"
          >提交</el-button>
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCommunityApi, addprojectlistApi, getshowprojectlistApi, editprojectlistApi } from '@/api/expenses/project'
export default {
  name: 'VueAdminTemplateMasterAddForm',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [],
      formData: {
        community_code: '',
        name: ''
      },
      rules: {
        community_code: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }]
      }

    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑项目' : '新增项目'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    /**
     * 回显
     */
    async getshowprojectlist(id) {
      this.$emit('update:showDialog', true)
      const { data } = await getshowprojectlistApi({ id })
      // console.log(data)
      this.formData = data[0]
    },
    /**
     * 新增
     */
    addprojectlistFn() {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        if (this.formData.id) {
          await editprojectlistApi(this.formData)
          this.$message.success('修改成功')
        } else {
          await addprojectlistApi(this.formData)
          this.$message.success('添加成功')
        }
        // console.log(this.formData)

        // 关闭弹框
        this.closeDialog()
        // 重新渲染
        this.$parent.getprojectlist()
      })
    },
    /**
     * 获取小区
     */
    async initData() {
      const res = await getCommunityApi()
      this.options = res.data
      // console.log(this.options)
    },
    closeDialog() {
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
      this.formData = {
        community_code: '',
        name: '',
        id: ''
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.el-input{
  width: 200px;
}
</style>
